var ws = {
    /** websocket连接对象 */
    _ws:null,
    /** 连接的主机 */
    _url:null,
    /** 连接网络 */
    connect: function(url){
        url && (this._url = url);
        if(this._ws){
            this._ws.close();
            this._ws = null;
        }else{
            this._ws = new WebSocket(this._url);
            this._ws.binaryType = "arraybuffer"; 
            this._ws.onopen = this._onopen.bind(this);
            this._ws.onmessage = this._onmessage.bind(this);
            this._ws.onerror = this._onerror.bind(this);
            this._ws.onclose = this._onclose.bind(this);
        }
    },
    /** 发生消息 */
    send: function(sd){
        if(sd instanceof DataView){
            cc.log("S [", sd.getUint16(4, true), "," , sd.getUint16(6, true), "]", sd.byteLength);
            sd = sd.buffer;
        }else if(sd instanceof ArrayBuffer){
            var dv = new DataView(sd);
            cc.log("S [", dv.getUint16(4, true), "," , dv.getUint16(6, true), "]", sd.byteLength);
        }else if(typeof(sd) == "object"){
            sd = JSON.stringify(sd);
            cc.log("S", sd);
        }else{
            cc.log("S", sd);
        } 
        this._ws.send(sd);
    },
    /** 网络连接成功 */
    _onopen: function(ev){
        cc.log("websocket open", this._url);
        var App = require("App");
        App.onConnect();
    },
    /** 网络收到消息 */
    _onmessage: function(ev){
        var ret;
        if (ev.data instanceof ArrayBuffer) {
            ret = new DataView(ev.data);
            //cc.log(ev.data.byteLength, ret, ret.getUint16);
            ret = [ret.getUint16(4, true), ret.getUint16(6, true), new DataView(ev.data, 8)];
            cc.log("R [",ret[0],",",ret[1],"]",ev.data.byteLength);
        }else{
            cc.log("R", ev.data);
            ret = JSON.parse(ev.data);
        }
        var App = require("App");
        App.onMessage(ret);
    },
    /** 网络错误 */
    _onerror: function(ev){
        cc.log("websocket error", ev);
    },
    /** 网络关闭 */
    _onclose: function(ev){
        cc.log("websocket close", ev);
        setTimeout(this.connect.bind(this), 3000);
    }
}

module.exports = ws;